package com.time.hellotime.components.profile;

import android.Manifest;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.Gson;
import com.tencent.smtt.sdk.WebSettings;
import com.time.hellotime.R;
import com.time.hellotime.app.AddressManager;
import com.time.hellotime.app.AppConfig;
import com.time.hellotime.base.BaseFragment;
import com.time.hellotime.common.event.BaseEvent;
import com.time.hellotime.components.JsListener;
import com.time.hellotime.components.WebDetailActivity;
import com.time.hellotime.servermodel.BasicBean;
import com.time.hellotime.utils.NetWorkUtils;
import com.time.hellotime.utils.ToastUtils;
import com.time.hellotime.views.ProgressWebView;
import com.time.hellotime.webserver.helper.WebServerManager;
import com.time.hellotime.webserver.listener.ResponseCallback;
import com.time.hellotime.webserver.request.requestsParamters.ProfileParameters;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;
import com.yanzhenjie.nohttp.BasicBinary;
import com.yanzhenjie.nohttp.Binary;
import com.yanzhenjie.nohttp.FileBinary;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * Created by Bing on 2017/10/25.
 * E-mail is tx16bing@163.com
 */

public class ProfileFragment extends BaseFragment implements JsListener {

    private ProgressWebView mWebView;
    private String profileUrl;

    @Override
    public void initContentView(View contentView) {
        EventBus.getDefault().register(this);
        mWebView = findView(R.id.profile_web_view);
        mWebView.getmWebView().getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        mWebView.setJsListener(this);
        profileUrl = new StringBuilder()
                .append(AddressManager.getInstance().getWebAddress())
                .append("/mine/")
                .append(application.isLogin() ? application.getAccount() : "-1")
                .append("/android/")
                .append(application.getVersionCode())
                .toString();
        mWebView.loadUrl(profileUrl);
    }

    @Override
    public int bindLayoutId() {
        return R.layout.fragment_profile;
    }

    @Override
    public void jsGoBack() {
    }

    @Override
    public void jsAvatar() {
        andPermission(101);
    }

    @Override
    public void jsSuggestion() {
        // 意见反馈
        FeedBackActivity.start(mContext);
    }

    @Override
    public void jsCommunicate() {
        CommunicateActivity.start(mContext);
    }

    @Override
    public void jsHiddenBottomTab(String tag, String url) {
        if (TextUtils.equals("false", tag)){
            // 不隐藏主界面底部导航栏
        }
        if (!TextUtils.isEmpty(url)){
            String mUrl = new StringBuilder().append(AddressManager.getInstance().getWebAddress()).append(url).toString();
            WebDetailActivity.start(mContext, tag, mUrl);
        }
    }

    @Override
    public void jsShare(String shareType, String whoShare, String id) {

    }

    @Override
    public void jsClearCache() {

    }

    @Override
    public void jsUpdateVersion(String url) {

    }

    @Override
    public void jsTelephone(String number) {

    }

    @Override
    public void jsExit() {
        // 退出登录
    }

    private void andPermission(int requestCode) {
        AndPermission.with(this)
                .requestCode(requestCode)
                .permission(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .callback(listener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(mContext, rationale)
                                .show();
                    }
                })
                .start();
    }

    // 权限回调监听
    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            AppConfig.getInstance().initDir();
            // 表示相册的存储的权限申请通过
            Album.image(mContext) // 选择图片。
                    .multipleChoice()
                    .requestCode(200)
                    .camera(true)
                    .columnCount(3)
                    .selectCount(1)
                    .widget(Widget.newDarkBuilder(mContext)
                            .title("图片")
                            .statusBarColor(ContextCompat.getColor(application, R.color.colorStatusBar))
                            .toolBarColor(ContextCompat.getColor(application, R.color.colorStatusBar))
                            .navigationBarColor(ContextCompat.getColor(application, R.color.colorStatusBar)) // Android5.0+的虚拟导航栏颜色。
                            .mediaItemCheckSelector(Color.WHITE, Color.GREEN) // 图片或者视频选择框的选择器。
                            .bucketItemCheckSelector(
                                    ContextCompat.getColor(application, R.color.colorPrimary),
                                    ContextCompat.getColor(application, R.color.colorPrimary)) // 切换文件夹时文件夹选择框的选择器。
                            .build())
                    .onResult(new Action<ArrayList<AlbumFile>>() {
                        @Override
                        public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                            if (null != result && !result.isEmpty()) {
                                String path = result.get(0).getPath();
                                List<String> paths = new ArrayList<>();
                                paths.add(path);
                                uploadAvatar(getString(R.string.command_uploadHeadImg), paths, "headPic");
                            }
                        }
                    })
                    .onCancel(new Action<String>() {
                        @Override
                        public void onAction(int requestCode, @NonNull String result) {
                        }
                    })
                    .start();
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            AppConfig.getInstance().initDir();
            // 即使是用户选择了不在询问还是会toast该提示语
            if (requestCode == 100) {
                ToastUtils.showShort("请检查是否开启了相机权限");
            } else if (requestCode == 101) {

                ToastUtils.showShort("请检查是否开启了文件读写权限");
            }

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(mContext, 404).show();
            }
        }
    };

    /**
     * 上传图片
     */
    private void uploadAvatar(String command, List<String> paths, String key) {
        if (!NetWorkUtils.isNetAvailable(application)) {
            ToastUtils.showShort(application.getString(R.string.network_error));
            return;
        }
        if (paths == null) {
            ToastUtils.showShort("请上传有效的图片路径");
            return;
        }

        if (paths.isEmpty()) {
            ToastUtils.showShort("上传图片不能为空");
            return;
        }

        ProfileParameters parameters = new ProfileParameters();
        parameters.setCommand(command);
        parameters.setUserId(application.getAccount());

        String url = null;
        try {
            url = new StringBuilder().append(AddressManager.getInstance().getAddress())
                    .append("?").append(getString(R.string.command))
                    .append("=").append(command)
                    .append("&").append(getString(R.string.data))
                    .append("=").append(URLEncoder.encode(new Gson().toJson(parameters), "UTF-8"))
                    .toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Request request = NoHttp.createStringRequest(url, RequestMethod.POST);
        request.add(application.getString(R.string.command), parameters.getCommand());
        request.add(application.getString(R.string.platform), parameters.getPlatform());
        request.add("userId", application.getAccount());
        List<Binary> binaries = new ArrayList<>();
        for (String path : paths) {
            File file = new File(path);
            BasicBinary fileBinary = new FileBinary(file);
            binaries.add(fileBinary);
        }
        request.add(key, binaries);
        request.setCancelSign(toString());
        WebServerManager.getInstance().add(mContext, request, new ResponseCallback<String>() {
                    @Override
                    public void onSucceed(int what, Response<String> response) {
                        String bean = response.get();
                        BasicBean basicBean = new Gson().fromJson(bean, BasicBean.class);

                        if (basicBean == null) {
                            return;
                        }

                        if (basicBean.isSuccess()) {
                            mWebView.reload();
                            Snackbar.make(getContentView(), "上传成功", Snackbar.LENGTH_SHORT).show();
                        } else {
                            ToastUtils.showShort(basicBean.getMsg());
                        }

                    }

                    @Override
                    public void onFailed(int what, Object tag, Exception exception, long networkMillis) {
                        Snackbar.make(getContentView(), "发送失败", Snackbar.LENGTH_SHORT).show();
                    }
                },
                409, true, false, true);
    }

    @Subscribe
    public void onEventMainThread(BaseEvent event){
        if (TextUtils.isEmpty(event.getBaseType())) {
            return;
        }
        if (TextUtils.equals(event.getBaseType(), getString(R.string.refresh_profile_fragment_data))) {
            mWebView.loadUrl(profileUrl);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
